﻿using System.Web.Mvc;

using NJ.Web.Models;

namespace NJ.Web.Filter
{
    public class AuthorizeFilterAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                var isLogin = CurUser.IsLogin();
                if (!isLogin)
                {
                    ActionResult actionResult = new EmptyResult();
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {

                        actionResult = new JavaScriptResult() { Script = "alert('请求超时，请重新登录！');top.location.href = '/Account/Login';" };
                    }
                    else
                    {
                        actionResult = new RedirectResult("/Account/Login");
                    }
                    CurUser.Clear();
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    filterContext.HttpContext.Response.StatusCode = 401;
                    filterContext.Result = actionResult;
                }
            }
        }
    }
}